<?php

class auth
{	
    public $userid        = NULL;
    public $username      = NULL;
    public $usercookie    = NULL;
    public $sessioncookie = NULL;
    public $session_id    = NULL;
	
	const _DEFAULT_TIMEOUT  = 60;
	const _TIMEOUT_ABSOLUTE =  1;	
	
    public function __construct() { 
		$this->table_section = PRFX."user_business_unit";
		$this->table_session = PRFX."session";
    }
	
    public function Login($user, $pass)
	{
		if (!$user || !$pass) {
			return FALSE;
		}
		
		$r =& Registry::get("MDB")->query("SELECT * FROM `".$this->table_section."` WHERE `Login`='".$user."' AND `Password`='".$pass."' AND `Show`='1';");
		if (PEAR::isError($r)) {
			die($r->getMessage().' ::: '.$r->getUserInfo());
		}
		if(!$r->numRows()) {
			return FALSE;
		}
		else {	
			$p = $r->fetchRow(MDB2_FETCHMODE_ASSOC);
		}

		$lifetime = time() + 365*24*60*60;
		setcookie("user_site_param[username]", $user,    $lifetime);
		setcookie("user_site_param[id]",       $p['id'], $lifetime);
		setcookie("user_site_param[txt_name]", $p['name'], $lifetime);
		setcookie("user_site_param[access]",   $p['access'], $lifetime);
		
		
        self::initSession();
        
		$r =& Registry::get("MDB")->query("UPDATE `".$this->table_session."` SET `userid`='".$p['id']."',`sess_start`=NOW(),`sess_expire`=DATE_ADD(NOW(),INTERVAL ".self::_DEFAULT_TIMEOUT." MINUTE),`last_activity`=NOW(),`ip`='".$_SERVER['REMOTE_ADDR']."',`user_agent`='".$_SERVER['HTTP_USER_AGENT']."' WHERE `session`='".$this->session_id."';");
		if (PEAR::isError($r)) {
			die($r->getMessage().' ::: '.$r->getUserInfo());
		}
        $this->usercookie['username'] = $user; 
        $this->usercookie['id']       = $p['id'];
		
        return TRUE;		
    }
	
    public function Logout()
	{
		if (self::Check_Auth()) {
			$r =& Registry::get("MDB")->query("DELETE from `".$this->table_session."` WHERE session='".$this->session_id."'");
			if (PEAR::isError($r)) {
				die($r->getMessage().' ::: '.$r->getUserInfo());
			}
        }		
		setcookie("user_site_param[username]", "", time() - 36000);
	   	setcookie("user_site_param[id]",       "", time() - 36000);
		setcookie("user_site_param[txt_name]", "", time() - 36000);		
		setcookie("user_site_param[access]",   "", time() - 36000);		
        setcookie("sessioncookie_site",        "", time() - 36000);
		setcookie("admin_site_param_be[name]", "", time() - 36000);
		setcookie("admin_site_param_be[id]",   "", time() - 36000);
		     
    }
	
	public function generateId()
	{
		$failsafe = 20;
		$randnum  = 0;
		while($failsafe--)
		{
			$randnum = md5(uniqid(microtime(), 1));
			if($randnum != "")
			{
				$r =& Registry::get("MDB")->query("SELECT * FROM `".$this->table_session."` WHERE `session` = MD5('".$randnum."');");
				if (PEAR::isError($r)) {
					die($r->getMessage().' ::: '.$r->getUserInfo());
				}			
				if ($r->numRows() == 0) break;
			}
		}
		$this->sessioncookie = $randnum;
		$this->session_id    = md5($randnum.$_SERVER['REMOTE_ADDR'] );
	} 
    
	public function initSession()
	{
		$sessioncookie = GetParam($_COOKIE, 'sessioncookie_site', NULL);
        $sess          = md5($sessioncookie.$_SERVER['REMOTE_ADDR']);
        
		$r =& Registry::get("MDB")->query("SELECT * FROM `".$this->table_session."` WHERE `session` = '".$sess."';");
		if (PEAR::isError($r)) {
			die($r->getMessage().' ::: '.$r->getUserInfo());
		}        
		if ($r->numRows())
		{
			$p = $r->fetchRow(MDB2_FETCHMODE_ASSOC);
			/* Session cookie exists, update time in session table */
			$r =& Registry::get("MDB")->query("UPDATE `".$this->table_session."` SET `last_activity`=NOW(), `sess_expire`=DATE_ADD(NOW(),INTERVAL ".self::_DEFAULT_TIMEOUT." MINUTE) WHERE `session`='".$sess."';");	  
			if (PEAR::isError($r)) {
				die($r->getMessage().' ::: '.$r->getUserInfo());
			}
			$this->sessioncookie = $sessioncookie;
			$this->session_id    = $p['session'];
		}
		else
		{
			self::generateId();
			setcookie("sessioncookie_site", $this->sessioncookie, time() + 43200);
			$r =& Registry::get("MDB")->query("INSERT INTO `".$this->table_session."` SET `last_activity`=NOW(),`session`='".$this->session_id."',`sess_expire`=DATE_ADD(NOW(),INTERVAL ".self::_DEFAULT_TIMEOUT." MINUTE);");	
			if (PEAR::isError($r)) {
				die($r->getMessage().' ::: '.$r->getUserInfo());
			}
		}
	}
	
    public function Check_Auth()
	{		
		$sess    = GetParam($_COOKIE, 'sessioncookie_site', NULL);
		$ucookie = GetParam($_COOKIE, 'user_site_param',    NULL);
        $sess    = md5($sess.$_SERVER['REMOTE_ADDR']);
        
		$r =& Registry::get("MDB")->query("DELETE FROM `".$this->table_session."` WHERE NOW() > sess_expire;"); /* PURGE SESSION */
		if (PEAR::isError($r)) {
			die($r->getMessage().' ::: '.$r->getUserInfo());
		}
        
		$row = NULL;
        $r =& Registry::get("MDB")->query("SELECT * FROM `".$this->table_session."` a LEFT JOIN `".$this->table_section."` b ON a.userid=b.ID WHERE session='".$sess."';");
		if (PEAR::isError($r)) {
			die($r->getMessage().' ::: '.$r->getUserInfo());
		}
        if(!$r->numRows()) {			
			return FALSE;
		} 
		else
		{
			$p = $r->fetchRow(MDB2_FETCHMODE_ASSOC);			
			if(($p['id'] == $ucookie['id']) && ($p['login'] == $ucookie['username']) && ($_SERVER['REMOTE_ADDR'] == $p['ip']))
			{
				$this->usercookie['username'] = $p['login'];
				$this->usercookie['id']       = $p['id'];			
				$this->sessioncookie = GetParam($_COOKIE, 'sessioncookie_site', NULL);
				$this->session_id = $sess;			
				if (!defined(self::_TIMEOUT_ABSOLUTE)){				
					$r =& Registry::get("MDB")->query("UPDATE `".$this->table_session."` SET `last_activity`=NOW(),`sess_expire`=DATE_ADD(NOW(), INTERVAL ".self::_DEFAULT_TIMEOUT." MINUTE) where `session` = '".$sess."';");
					if (PEAR::isError($r)) {
						die($r->getMessage().' ::: '.$r->getUserInfo());
					}
				} else {
					$r =& Registry::get("MDB")->query("UPDATE `".$this->table_session."` SET last_activity=NOW() WHERE `session` = '".$sess."';");
					if (PEAR::isError($r)) {
						die($r->getMessage().' ::: '.$r->getUserInfo());
					}
				}
				return TRUE;
			}
			else {
				return FALSE;
			}
		}
    }
}
     
?>